<template>
  <el-dialog
    :visible.sync="dialogVisible"
    :title="titleStatus === 'add' ? '添加角色' : '编辑角色'"
    width="900px"
    :before-close="handleClose"
  >
    <el-form :model="form" :rules="rules" ref="ruleForm" label-width="120px">
      <el-form-item label="角色名称" prop="role_name">
        <el-input
          v-model="form.role_name"
          placeholder="请输入角色名称"
          clearable
          show-word-limit
          maxlength="10"
        ></el-input>
      </el-form-item>
      <el-form-item label="角色描述">
        <el-input
          v-model="form.role_desc"
          type="textarea"
          clearable
          :rows="3"
          placeholder="请输入角色描述"
          maxlength="50"
          show-word-limit
        ></el-input>
      </el-form-item>
      <el-form-item label="角色状态">
        <el-radio v-model="form.status" :label="1">启用中</el-radio>
        <el-radio v-model="form.status" :label="2">禁用</el-radio>
      </el-form-item>
      <el-form-item label="权限配置">
        <div class="flex">
          <div class="menu">
            <el-tree
              ref="tree"
              :data="data"
              node-key="menu_id"
              :props="defaultProps"
              show-checkbox
              :default-expanded-keys="defaultCheckedTreeArray"
              @node-click="handleNodeClick"
              @check="
                (click, checked) => {
                  handleChangeCheckTree(click, checked);
                }
              "
              @check-change="handleCheckChange"
            >
              <span class="custom-tree-node" slot-scope="{ node, data }">
                <span :class="handleClass(data) ? 'text-blue-400' : ''">
                  {{ data.menu_name }}
                </span>
              </span>
            </el-tree>
          </div>
          <el-card class="jurisdiction">
            <div class="flex flex-wrap">
              <el-checkbox-group
                v-if="jurisdictionArr.length > 0"
                v-model="checkedArr"
                @change="handleChangeCheckbox"
              >
                <el-checkbox
                  v-for="item in jurisdictionArr"
                  :key="item.id"
                  :label="item.id"
                >
                  {{ item.name }}
                </el-checkbox>
              </el-checkbox-group>
              <p v-else class="text-gray-400">该页面暂无权限</p>
            </div>
          </el-card>
        </div>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" @click="handleConfirm">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import {
  getAccessData,
  getRoleAccess,
  postAddData,
  putEditData
} from "@/api/config/roleList";

export default {
  name: "",
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    titleStatus: {
      type: String,
      default: "add"
    },
    rowId: {
      type: Number
    },
    data: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      form: {
        role_name: "",
        role_desc: "",
        status: 1,
        access_ids: ""
      },
      rules: {
        role_name: [
          { required: true, message: "请输入角色名称", trigger: "blur" }
        ]
      },
      defaultProps: {
        children: "children",
        label: "menu_name"
      },
      //当前节点所对应的权限数组
      jurisdictionArr: [],
      // 已选择的
      checkedArr: [],
      // 已选择的树节点
      checkedTreeArr: [],
      defaultCheckedTreeArray: []
    };
  },

  watch: {
    titleStatus: async function(newValue, oldValue) {
      if (newValue === "edit") {
        const { data } = await getRoleAccess(this.rowId);
        this.form.role_name = data.role_name;
        this.form.role_desc = data.role_memo;
        this.form.status = data.status;
        this.form.access_ids = "";
        this.checkedArr = data.access_ids;

        this.handleSelectedTree();
      } else {
        this.checkedArr = [];
        this.checkedTreeArr = [];
        this.defaultCheckedTreeArray = [];
        this.$refs.tree.store._getAllNodes().map(n => (n.expanded = false));
        this.$refs.tree.setCheckedKeys([]);
      }
    }
  },

  created() {},

  methods: {
    handleSelectedTree() {
      let arr = [];
      this.data.forEach(data => {
        if (data.children && data.children.length > 0) {
          data.children.map(item => {
            if (item.access && item.access.length > 0) {
              let bool = item.access.every(i => {
                return this.checkedArr.includes(i.id);
              });
              if (bool) arr.push(item.menu_id);
            }
          });
        }
      });
      // this.defaultCheckedTreeArray = arr;
      this.$refs.tree.setCheckedKeys(arr);
    },
    handleChangeCheckbox(value) {
      this.handleSelectedTree();
    },
    handleCheckChange(data, state, has) {
      // console.log(data, state, has, 12312);
      // // 从已选的树节点 循环找到里的二级子节点
      // if (state) {
      //   if (data.children && data.children.length > 0) {
      //     data.children.forEach(item => {
      //       if (item.access && item.access.length > 0) {
      //         item.access.forEach(i => {
      //           if (this.checkedArr.indexOf(i.id) === -1)
      //             this.checkedArr.push(i.id);
      //         });
      //       }
      //     });
      //   } else if (data.access && data.access.length > 0) {
      //     data.access.forEach(i => {
      //       if (this.checkedArr.indexOf(i.id) === -1)
      //         this.checkedArr.push(i.id);
      //     });
      //   }
      // } else {
      //   if (data.children && data.children.length > 0) {
      //     data.children.forEach(item => {
      //       if (item.access && item.access.length > 0) {
      //         item.access.forEach(i => {
      //           this.checkedArr.splice(this.checkedArr.indexOf(i.id), 1);
      //         });
      //       }
      //     });
      //   } else if (data.access && data.access.length > 0) {
      //     data.access.forEach(i => {
      //       // this.checkedArr.push(i.id);
      //       console.log(this.checkedArr.indexOf(i.id));
      //       this.checkedArr.splice(this.checkedArr.indexOf(i.id), 1);
      //     });
      //   }
      // }
      // console.log(this.checkedArr);
    },
    handleChangeCheckTree(click, checked) {
      // 最新的全选列表
      let newTreeCheckedArr = checked.checkedKeys;
      let filterArr = this.checkedTreeArr.filter(item => {
        if (item.access && item.access.length > 0) {
          return !newTreeCheckedArr.includes(item.menu_id);
        }
      });
      console.log(filterArr, 111111);
      let delArr = [];
      filterArr.forEach(item => {
        if (item.access && item.access.length > 0) {
          item.access.forEach(i => {
            delArr.push(i.id);
          });
        }
      });
      delArr.forEach(item => {
        this.checkedArr.splice(this.checkedArr.indexOf(item), 1);
      });

      // 获取已选的树节点  如果没有已选 或者置为空 则权限清空
      this.checkedTreeArr = checked.checkedNodes;
      if (this.checkedTreeArr.length === 0) {
        this.checkedArr = [];
        return;
      }
      let arr = [];
      // 从已选的树节点 循环找到里的二级子节点
      this.checkedTreeArr.forEach(item => {
        if (item.children && item.children.length > 0) {
        } else if (item.access && item.access.length > 0) {
          item.access.forEach(i => {
            arr.push(i.id);
          });
        }
      });
      // this.checkedArr = arr;
      this.checkedArr.push(...arr);
      this.checkedArr = [...new Set(this.checkedArr)];
      console.log(this.checkedArr);
    },
    handleClass(data) {
      let bool;
      if (data.children && data.children.length > 0) {
        data.children.map(item => {
          if (item.access && item.access.length > 0) {
            bool = item.access.some(i => {
              return this.checkedArr.includes(i.id);
            });
          }
        });
      } else {
        if (data.access && data.access.length > 0) {
          bool = data.access.some(item => {
            return this.checkedArr.includes(item.id);
          });
        }
      }
      return bool;
    },
    async handleGetAccessData() {
      const res = await getAccessData(1);
      this.data = res.data;
    },
    handleNodeClick(data) {
      //判断所点击的节点是否含有access权限数组
      if (
        data.access &&
        typeof data.access === "object" &&
        data.access !== null
      ) {
        this.jurisdictionArr = data.access;
      } else {
        this.jurisdictionArr = [];
      }
    },
    handleClose() {
      this.form = {
        role_name: "",
        role_desc: "",
        status: 1,
        access_ids: ""
      };
      this.checkedArr = [];
      this.jurisdictionArr = [];
      // 已选择的树节点
      this.checkedTreeArr = [];
      this.$emit("update:dialogVisible", false);
      this.$emit("update:titleStatus", "add");
    },
    handleConfirm() {
      this.$refs.ruleForm.validate(async valid => {
        if (valid) {
          let res = null;
          let newCheckedArr = [...new Set(this.checkedArr)];
          this.form.access_ids = newCheckedArr.join(",");
          if (this.titleStatus === "add") {
            res = await postAddData(this.form);
          } else {
            res = await putEditData(this.rowId, this.form);
          }
          if (res.code === 200) {
            this.$emit("refresh");
            this.$message.success("操作成功");
            this.handleClose();
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    }
  }
};
</script>
<style lang="scss" scoped>
::v-deep .el-form-item__content {
  padding-right: 40px;
}

::v-deep
  .el-tree
  > .el-tree-node
  > .el-tree-node__children
  > .el-tree-node
  > .el-tree-node__children {
  display: flex;
  flex-wrap: wrap;
}

.menu {
  width: 200px;
  height: 300px;
  overflow: auto;
}

.jurisdiction {
  width: 550px;
  height: 300px;
}
</style>
